package com.opennews.openplatform.familyexpenseapi.config

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.opennews.openplatform.myspringbootcore.util.LocalDateTimeToUTCSerializer
import com.opennews.openplatform.myspringbootcore.util.UTCToLocalDateTimeDeserializer
import jakarta.annotation.PostConstruct
import org.modelmapper.ModelMapper
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.web.client.RestTemplate
import java.time.LocalDateTime
import java.util.*

@Configuration
class AppConfig {
    @Value("\${app.system.time-zone}")
    private val timeZone: String? = null

    @Bean
    fun modelMapper(): ModelMapper {
        return ModelMapper()
    }

    @Bean
    fun objectMapper(): ObjectMapper {
        val objectMapper = ObjectMapper()

        // Ensure dates are serialized as ISO-8601.
        // The result would be like "2024-11-20T07:11:50Z".
        val javaTimeModule = JavaTimeModule().apply {
            addSerializer(LocalDateTime::class.java, LocalDateTimeToUTCSerializer())
            addDeserializer(LocalDateTime::class.java, UTCToLocalDateTimeDeserializer())
        }

        objectMapper.registerModule(javaTimeModule)
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)

        return objectMapper
    }

    @Bean
    fun restTemplate(): RestTemplate {
        return RestTemplate()
    }

    @PostConstruct
    fun setUpTimeZone() {
        // Sets the default time zone using the injected value.
        TimeZone.setDefault(TimeZone.getTimeZone(timeZone))
    }
}